package service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import constant.Context;
import lombok.extern.slf4j.Slf4j;
import service.ClipboardService;
import service.ImageService;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Objects;

/**
 * @Author: gaoxu11
 * @Date: 2022/5/13 1:38 AM
 * @Description:GImG.ImageServiceImpl
 */
@Slf4j
public class ImageServiceImpl implements ImageService {

    private ClipboardService clipboardService = new ClipboardServiceImpl();

    @Override
    public String upload() throws UnsupportedEncodingException {
        String res = "";
        try {
            log.info("ImageServiceImpl upload [开始获取剪切板图片]");
            File clipboardFile = clipboardService.getClipboardFile();
            if (Objects.isNull(clipboardFile)) {
                return res;
            }
            log.info("ImageServiceImpl upload [开始上传图片到服务器]");
            HttpResponse response = HttpRequest.post(Context.WEB_SERVER)
                    .form("photos", clipboardFile)
                    .execute();
            if (response.getStatus() == 200) {
                res = new String(response.bodyBytes(), "UTF-8");
                JSONObject jsonObject = JSONUtil.parseObj(res);
                String data = jsonObject.get("data", String.class);

                if (Context.MARKDOWN) {
                    data = String.format("![](%s)", data);
                }
                boolean flag = clipboardService.writeToClipboard(data);
                res = data;
                log.info("ImageServiceImpl upload [已将链接粘贴到剪切板] Url:{}", data);
            }
        } catch (Exception e) {
            log.error("ImageServiceImpl upload [上传图片异常]");
        }
        return res;
    }
}
